<template>
  <div class="video-records">
    <div class="con-top">
      <el-date-picker
        v-model="recordDate"
        class="c-date-editor"
        popper-class="c-date-editor-picker"
        type="datetimerange"
        value-format="yyyy-MM-dd HH:mm"
        format="yyyy-MM-dd HH:mm"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :clearable="false"
        :editable="false"
        :append-to-body="false"
        :default-time="['00:00:00', '23:59:59']"
        size="mini"
      />
      <el-select v-model="recordDuration" class="c-select" popper-class="c-select-dropdown un-to-body" :popper-append-to-body="false" placeholder="录像时间">
        <el-option v-for="item in recordDurationSelect" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
      </el-select>
      <el-select v-model="storageType" class="c-select" popper-class="c-select-dropdown un-to-body" :popper-append-to-body="false" placeholder="录像类型">
        <el-option v-for="item in storageTypeSelect" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
      </el-select>
      <div class="c-button on" @click="getList">查询</div>
      <div class="c-button" @click="reset">重置</div>
    </div>
    <div ref="recordList" class="con-bottom" v-loading="!list">
      <c-scroll v-if="list?.length">
        <div class="record-list">
          <template v-for="(item, index) in list">
            <div v-if="!forPage || index >= (pageNum - 1) * pageSize && index < pageNum * pageSize" class="item" :class="{'on': look?.id === item.id}">
              <span :c-tip="item.f" c-tip-auto>{{ item.f }}</span>
              <i class="iconfont look" :class="look?.id === item.id ? 'icon-shipinzujian_icon_chakan_s' : 'icon-shipinzujian_icon_chakan_n'" c-tip="查看" @click="playRecord(item)" />
              <i class="iconfont icon-tongyong_icon_xiazai" c-tip="下载" @click="download(item)" />
            </div>
          </template>
        </div>
      </c-scroll>
      <div v-else-if="list" class="c-no-datas">暂无数据</div>
    </div>
    <div v-if="forPage && list?.length" class="con-page">
      <span class="total">共{{ list.length }}条</span>
      <el-pagination
        layout="prev, pager, next"
        :current-page="pageNum"
        :page-size="pageSize"
        :total="list.length"
        :pager-count="5"
        background
        @current-change="loadPage"
      />
    </div>
  </div>
</template>
<script>
import { queryVideoList } from '@/api/video/video';
export default {
  props: ['deviceCode', 'channelCode', 'channelName', 'forPage'],
  data() {
    return {
      recordDate: '', //录像时间
      pickerOptions: {}, //录像时间选择参数
      recordDuration: '5', //视频时长
      recordDurationSelect: [{ //视频时长下拉选择
        dictLabel: '5分钟',
        dictValue: '5'
      },{
        dictLabel: '10分钟',
        dictValue: '10'
      },{
        dictLabel: '15分钟',
        dictValue: '15'
      }],
      storageType: '1', //录像类型
      storageTypeSelect: [{ //录像类型下拉选择
        dictLabel: '前端录像',
        dictValue: '0'
      },{
        dictLabel: '后端录像',
        dictValue: '1'
      }],
      list: null, //列表
      recordFiles: [], //录像文件列表
      look: false, //录像查看
      pageNum: 1, //分页时页码
      pageSize: 0, //分页时每页条数
      height: 0, //容器高度
    };
  },
  watch: {
    channelCode() {
      this.getList();
    }
  },
  async mounted() {
    this.pickerOptions = {
      // shortcuts: [{
      //   text: '今日',
      //   onClick(picker) {
      //     const start = new Date();
      //     const end = new Date();
      //     picker.$emit('pick', [start, end]);
      //   }
      // }, {
      //   text: '近3天',
      //   onClick(picker) {
      //     const start = new Date();
      //     const end = new Date();
      //     start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
      //     picker.$emit('pick', [start, end]);
      //   }
      // }, {
      //   text: '近7天',
      //   onClick(picker) {
      //     const start = new Date();
      //     const end = new Date();
      //     start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
      //     picker.$emit('pick', [start, end]);
      //   }
      // }],
      onPick: ({ maxDate, minDate }) => {
        this.selectDate = minDate.getTime();
        if(maxDate) {
          this.selectDate = '';
        }
      },
      disabledDate: (time) => {
        const today = new Date(this.$moment().format("YYYY-MM-DD") + ' 23:59:59').getTime();
        if(this.selectDate) {
          const one = 3600000 * 24 * 6;
          const minTime = this.selectDate - one;
          const maxTime = this.selectDate + one;
          let day = time.getTime();
          return (day < minTime || day > maxTime || day > today);
        }else{
          return time.getTime() > today;
        }
      }
    };
    try{
      await this.getMultipleDicts(['video_record_duration', 'storageType']).then(resp => {
        if(resp.data['video_record_duration'].length) {
          this.recordDurationSelect = resp.data['video_record_duration'];
        }
        if(resp.data['storageType'].length) {
          this.storageTypeSelect = resp.data['storageType'];
        }
      });
    }catch(e) {
      //console.log(e)
    }
    this.reset();
    this.getList();
    if(!this.forPage) {
      return false;
    }
    this.resizeObserver = new ResizeObserver(() => {
      if(this.$el.offsetHeight && this.$el.offsetHeight !== this.height) {
        this.height = this.$el.offsetHeight;
        this.loadPage();
      }
    });
    this.resizeObserver.observe(this.$el);
  },
  methods: {
    /**
     * 加载分页
     */
    loadPage(pageNum = 1) {
      if(!this.forPage) {
        return false;
      }
      this.pageNum = pageNum;
      this.$nextTick(() => {
        this.pageSize = Math.floor(this.$refs.recordList.offsetHeight / 45);
      });
    },
    /**
     * 查看录像
     */
    playRecord(item) {
      if(this.look?.id === item.id) {
        this.closeRecord();
        return false;
      }
      this.look = item;
      this.$emit('recordDownload', {
        recordLook: this.look
      });
    },
    /**
     * 关闭录像
     */
    closeRecord() {
      this.look = false;
      this.$emit('recordDownload', {
        recordLook: this.look
      });
    },
    /**
     * 下载
     */
    download(item) {
      this.$emit('recordDownload', {
        show: 3,
        datas: [{
          deviceCode: this.deviceCode,
          channelCode: this.channelCode,
          channelName: this.channelName,
          videoDate: [item.startF, item.endF],
          storageType: item.storageType
        }]
      });
    },
    /**
     * 重置
     */
    reset() {
      this.recordDuration = this.recordDurationSelect[0].dictValue;
      this.storageType = this.storageTypeSelect[this.storageTypeSelect.length - 1].dictValue;
      const start = this.$moment().format("YYYY-MM-DD") + ' 00:00';
      const end = this.$moment().format('YYYY-MM-DD HH:mm');
      this.recordDate = [start, end];
    },
    /**
     * 查询录像列表
     */
    getList(query) {
      if(this.list === 0) {
        return false;
      }
      this.list = 0;
      this.recordFiles = [];
      this.closeRecord();
      if(!this.deviceCode || !this.channelCode) {
        this.list = [];
        query && $message.w('请选择摄像机');
        return false;
      }
      const params = {
        deviceCode: this.deviceCode, //设备编码
        channelCode: this.channelCode, //通道编码
        storageType: Number(this.storageType), //存储类型 0-前端存储；1-中心存储
        recordType: 2, //录像类型：0-普通录像，1-报警录像，2-全部查询
        startTime: this.recordDate[0] + ':00', //开始时间(格式：yyyy-MM-dd HH:mm:ss）
        endTime: this.recordDate[1] + ':59', //开始时间(格式：yyyy-MM-dd HH:mm:ss）
        currentPage: 1, //当前页面
        pageSize: 86400 //每页条数
      };
      queryVideoList(params).then(resp => {
        this.list = [];
        if(resp.data?.videos.length) {
          this.recordFiles = resp.data?.videos;
          this.loadList();
          this.loadPage();
        }
      }).catch(() => {
        this.list = [];
      });
    },
    /**
     * 加载时间段列表
     */
    loadList() {
      const list = [];
      let start = new Date(this.recordDate[0] + ':00').getTime();
      const end = new Date(this.recordDate[1] + ':59').getTime();
      for(;;) {
        const s = start;
        let e = start += Number(this.recordDuration) * 60 * 1000;
        e >= end && (e = end);
        const sF = this.$moment(s).format('YYYY-MM-DD HH:mm:ss');
        const eF = this.$moment(e).format('YYYY-MM-DD HH:mm:ss');
        const records = this.fitRecords(sF, eF);
        if(records.length) {
          list.push({
            id: this.UUID(),
            start: s,
            startF: sF,
            end: e,
            endF: eF,
            f: sF + '~' + eF,
            storageType: Number(this.storageType),
            records
          });
        }
        if(e >= end) {
          break;
        }
      }
      this.list = list;
    },
    /**
     * 匹配录像
     */
    fitRecords(start, end) {
      return this.recordFiles.filter(item => item.startTime < end && item.endTime > start);
    },
  },
  beforeDestroy() {
    this.closeRecord();
    this.resizeObserver && this.resizeObserver.disconnect();
  }
}
</script>
<style lang="scss" scoped>
.video-records{
  width: 100%;
  height: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0 !important;
  .con-top{
    padding: 0 12px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    .c-select{
      width: calc(50% - 3px);
      margin-top: 12px;
    }
    .c-button{
      width: calc(50% - 3px);
      margin-top: 12px;
    }
    /deep/ .el-input__icon.el-range__close-icon{
      width: 0px;
    }
  }
  .con-bottom{
    flex: 1;
    overflow: hidden;
    margin-top: 12px;
    position: relative;
    .record-list{
      width: 100%;
      color: #fff;
      .item{
        height: 45px;
        padding: 0 12px;
        display: flex;
        align-items: center;
        position: relative;
        line-height: 1;
        span{
          flex: 1;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 12px;
        }
        i{
          font-size: 20px;
          margin-left: 6px;
          cursor: pointer;
          &:hover{
            opacity: 0.6;
          }
          &:active{
            opacity: 0.8;
          }
        }
        &:after{
          content: "";
          height: 1px;
          width: calc(100% - 24px);
          background: rgba(255,255,255,0.2);
          position: absolute;
          left: 12px;
          bottom: 0;
        }
        &:last-child:after{
          display: none;
        }
        &:hover, &.on{
          background: rgba(255,255,255,0.2);
        }
      }
    }
  }
  .con-page{
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
    height: 46px;
    background: rgba(0, 0, 0, 0.7);
    margin-bottom: -12px;
    padding: 0 12px;
    .total{
      color: #fff;
      font-size: 12px;
      margin-right: 6px;
    }
    .el-pagination{
      margin: 0;
      padding: 0;
      overflow: hidden;
      /deep/ button, /deep/ li{
        background: none !important;
        height: 22px;
        line-height: 22px;
        margin: 0 2px;
        min-width: 22px;
        padding: 0 4px;
        color: #fff !important;
        &:before{
          line-height: inherit;
        }
        i{
          line-height: 24px;
        }
        &:hover{
          opacity: 0.6;
        }
        &:active{
          opacity: 0.8;
        }
        &.active{
          background: rgba(255,255,255,0.2) !important;
          border-radius: 4px;
          opacity: 1;
        }
        &:disabled{
          opacity: 0.4;
        }
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.t{
  .video-records{
    .con-bottom{
      .record-list{
        color: #E8F3FE;
        .item{
          span{
            font-size: 14px;
          }
          &:after{
            background: rgba(232, 243, 254, 0.2);
          }
          &:hover{
            background: rgba(79,159,255,0.4);
          }
          &.on{
            span, .look{
              color: #4F9FFF;
            }
            background: rgba(79,159,255,0.4);
          }
        }
      }
    }
    .con-page{
      .total{
        color: #E8F2FE;
      }
      .el-pagination{
        /deep/ button, /deep/ li{
          color: #E8F3FE !important;
          &.active{
            background: #4F9FFF !important;
          }
        }
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.l2{
  .video-records{
    .con-bottom{
      .record-list{
        .item{
          span{
            font-size: 14px;
          }
          &:after{
            background: rgba(255, 255, 255, 0.2);
          }
          &:hover{
            background: rgba(2, 137, 109, 0.4);
          }
          &.on{
            span, .look{
              color: #F9FF6C;
            }
            background: rgba(2, 137, 109, 0.4);
          }
        }
      }
    }
    .con-page{
      .el-pagination{
        /deep/ button, /deep/ li{
          &.active{
            background: #02896D !important;
          }
        }
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.g{
  .video-records{
    .con-bottom{
      .record-list{
        color: #E4E7C1;
        .item{
          span{
            font-size: 14px;
          }
          i{
            color: #FFEEB1;
          }
          &:after{
            background: rgba(228, 231, 193, 0.2);
          }
          &:hover{
            background: rgba(100, 86, 46, 0.4);
          }
          &.on{
            span, .look{
              color: #FFFA28;
            }
            background: rgba(100, 86, 46, 0.4);
          }
        }
      }
    }
    .con-page{
      .total{
        color: #E4E7C1;
      }
      .el-pagination{
        /deep/ button, /deep/ li{
          color: #FFEEB1 !important;
          &.active{
            background: #9F9853 !important;
          }
        }
      }
    }
  }
}
</style>
